package cn.pugle.slf4j;

import org.slf4j.helpers.Util;
import org.slf4j.impl.StaticLoggerBinder;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Created by tzp on 15-9-29.
 * slf4j 利用 同包同名的类进行替换 以实现和其他日志框架的对接和随意切换
 * slf4j-api slf4j-log4j log4j-over-slf4j
 */
public class SameNameClassTest4SLF4j {
    private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class";

    public static void main(String[] args) {
        singleImplementationSanityCheck();
        StaticLoggerBinder singleton = StaticLoggerBinder.getSingleton();
        System.out.println(singleton.getClass().getResource(""));
    }

    //来自slf4j-api.jar org.slf4j.LoggerFactory
    private static void singleImplementationSanityCheck() {
        try {
            ClassLoader loggerFactoryClassLoader = SameNameClassTest4SLF4j.class
                    .getClassLoader();
            Enumeration paths;
            if (loggerFactoryClassLoader == null) {
                paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
            } else {
                paths = loggerFactoryClassLoader
                        .getResources(STATIC_LOGGER_BINDER_PATH);
            }
            // use Set instead of list in order to deal with  bug #138
            // LinkedHashSet appropriate here because it preserves insertion order during iteration
            Set implementationSet = new LinkedHashSet();
            while (paths.hasMoreElements()) {
                URL path = (URL) paths.nextElement();
                System.out.println(path);
                implementationSet.add(path);
            }
            if (implementationSet.size() > 1) {
                Util.report("Class path contains multiple SLF4J bindings.");
                Iterator iterator = implementationSet.iterator();
                while (iterator.hasNext()) {
                    URL path = (URL) iterator.next();
                    Util.report("Found binding in [" + path + "]");
                }
                Util.report("See " + "xx" + " for an explanation.");
            }
        } catch (IOException ioe) {
            Util.report("Error getting resources from path", ioe);
        }
    }
}
